<template>
  <div class="user-management">
    <!-- 主要内容区域 - 添加水平和垂直滚动容器，包裹整个页面内容 -->
    <div class="main-content-wrapper">
    <el-card>
      <!-- 移除卡片头部标题 -->
      
      <!-- 搜索区域 -->
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20" align="middle">
          <el-col :span="6">
            <el-form-item label="姓名" inline>
              <el-input v-model="searchForm.name" placeholder="请输入" style="width: 180px;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机号" inline>
              <el-input v-model="searchForm.phone" placeholder="请输入" style="width: 180px;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" inline>
              <el-select v-model="searchForm.deptId" placeholder="请选择" style="width: 180px;">
                <el-option label="全部" value="" />
                <!-- 部门选项将在组件挂载时加载 -->
                <el-option v-for="dept in deptOptions" :key="dept.id" :label="dept.name" :value="dept.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right;">
            <el-form-item>
              <el-button type="primary" @click="handleSearch" style="margin-right: 10px;">搜索</el-button>
              <el-button @click="handleReset">清空</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" inline>
              <el-select v-model="searchForm.status" placeholder="请选择" style="width: 180px;">
                <el-option label="全部" value="" />
                <el-option label="正常" value="1" />
                <el-option label="停用" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <!-- 操作按钮 - 置于左边 -->
      <div class="action-buttons-left" style="margin-bottom: 20px;">
        <el-button type="primary" @click="handleAdd">+ 添加用户</el-button>
        <el-button @click="handleBatchCheck">批量删除</el-button>
      </div>
      
      <el-table 
        :data="userList" 
        stripe 
        style="width: 100%; min-width: 1320px; font-size: 14px;"
        :header-cell-style="{ 'font-size': '14px', 'padding': '10px 12px' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="image" label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.image" />
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="部门" width="120" />
        <el-table-column prop="roleName" label="角色" width="120" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后操作时间" width="200" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <div style="display: flex; gap: 10px; justify-content: center;">
              <el-button type="primary" size="small" @click="handleEdit(row)">修改</el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" maxlength="11" show-word-limit />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="formData.gender" placeholder="请选择性别">
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="正常" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select v-model="formData.deptId" placeholder="请选择部门">
            <el-option v-for="dept in deptOptions" :key="dept.id" :label="dept.name" :value="dept.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="formData.roleId" placeholder="请选择角色">
            <el-option v-for="role in roleOptions" :key="role.id" :label="role.name" :value="role.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" maxlength="50" show-word-limit />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'UserManagement',
  setup() {
    // 搜索表单
    const searchForm = reactive({
      name: '',
      phone: '',
      deptId: '',
      status: ''
    })
    
    // 用户列表数据
    const userList = ref([])
    
    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 对话框相关
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const formRef = ref(null)
    
    // 表单数据
    const formData = reactive({
      id: '',
      username: '',
      name: '',
      phone: '',
      email: '',
      gender: '1',
      status: '1',
      deptId: '',
      roleId: '',
      image: '',
      remark: ''
    })
    
    // 部门和角色选项
    const deptOptions = ref([])
    const roleOptions = ref([])
    
    // 批量选中的数据
    const selectedRows = ref([])
    
    // 表单验证规则
    const formRules = reactive({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 1, max: 20, message: '用户名长度在 1 到 20 个字符', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 1, max: 20, message: '姓名长度在 1 到 20 个字符', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ],
      deptId: [
        { required: true, message: '请选择部门', trigger: 'change' }
      ],
      roleId: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],

      remark: [
        { max: 50, message: '备注长度不能超过 50 个字符', trigger: 'blur' }
      ]
    })
    
    // 加载部门选项
    const loadDeptOptions = async () => {
      try {
        const response = await axios.get('/api/depts/list')
        const result = response.data
        if (result.code === 1 && Array.isArray(result.data)) {
          deptOptions.value = result.data
        }
      } catch (error) {
        console.error('加载部门选项失败', error)
      }
    }
    
    // 加载角色选项
    const loadRoleOptions = async () => {
      try {
        const response = await axios.get('/api/roles')
        const result = response.data
        if (result.code === 1 && result.data && Array.isArray(result.data.rows)) {
          roleOptions.value = result.data.rows
        }
      } catch (error) {
        console.error('加载角色选项失败', error)
      }
    }
    
    // 获取用户列表
    const getUserList = async () => {
      try {
        const params = {
          ...searchForm,
          page: pagination.currentPage,
          pageSize: pagination.pageSize
        }
        
        const response = await axios.get('/api/users', {
          params: params
        })
        
        const result = response.data
        
        if (result && typeof result === 'object') {
          if (result.code === 1) {
            if (result.data && Array.isArray(result.data.rows)) {
              userList.value = result.data.rows
              pagination.total = Number(result.data.total) || 0
              
              if (userList.value.length === 0) {
                ElMessage.info('暂无数据')
              }
            } else {
              ElMessage.error('响应数据格式错误')
            }
          } else {
            ElMessage.error(result.msg || '获取用户列表失败')
          }
        } else {
          ElMessage.error('获取用户列表失败')
        }
      } catch (error) {
        ElMessage.error('获取用户列表失败')
      }
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      getUserList()
    }
    
    // 重置
    const handleReset = () => {
      searchForm.name = ''
      searchForm.phone = ''
      searchForm.deptId = ''
      searchForm.status = ''
      pagination.currentPage = 1
      getUserList()
    }
    
    // 重置表单数据
    const resetForm = () => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
      formData.id = ''
      formData.username = ''
      formData.name = ''
      formData.phone = ''
      formData.email = ''
      formData.gender = '1'
      formData.status = '1'
      formData.deptId = ''
      formData.roleId = ''
      formData.image = ''
      formData.remark = ''
    }
    
    // 添加用户
    const handleAdd = () => {
      dialogTitle.value = '添加用户'
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑用户
    const handleEdit = async (row) => {
      dialogTitle.value = '修改用户'
      resetForm()
      
      try {
        // 根据ID查询用户详情
        const response = await axios.get(`/api/users/${row.id}`)
        const result = response.data
        
        if (result.code === 1 && result.data) {
          // 填充表单数据
          formData.id = result.data.id
          formData.username = result.data.username
          formData.name = result.data.name
          formData.phone = result.data.phone
          formData.email = result.data.email
          formData.gender = String(result.data.gender)
          formData.status = String(result.data.status)
          formData.deptId = String(result.data.deptId)
          formData.roleId = String(result.data.roleId)
          formData.image = result.data.image
          formData.remark = result.data.remark
          
          dialogVisible.value = true
        } else {
          ElMessage.error(result.msg || '获取用户详情失败')
        }
      } catch (error) {
        ElMessage.error('获取用户详情失败')
      }
    }
    
    // 删除用户
    const handleDelete = (row) => {
      ElMessageBox.confirm(`确定要删除用户「${row.name}」吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await axios.delete(`/api/users/${row.id}`)
          const result = response.data
          
          if (result.code === 1) {
            ElMessage.success('删除成功')
            getUserList()
          } else {
            ElMessage.error(result.msg || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 批量删除
    const handleBatchCheck = () => {
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的用户')
        return
      }
      
      const ids = selectedRows.value.map(row => row.id).join(',')
      const names = selectedRows.value.map(row => row.name).join('、')
      
      ElMessageBox.confirm(`确定要删除用户「${names}」吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await axios.delete(`/api/users/${ids}`)
          const result = response.data
          
          if (result.code === 1) {
            ElMessage.success('批量删除成功')
            getUserList()
            selectedRows.value = []
          } else {
            ElMessage.error(result.msg || '批量删除失败')
          }
        } catch (error) {
          ElMessage.error('批量删除失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        
        let response
        if (formData.id) {
          // 修改 - 按照接口文档要求，ID应该放在请求体中
          const submitData = {
            id: formData.id,
            username: formData.username,
            name: formData.name,
            phone: formData.phone,
            email: formData.email,
            gender: Number(formData.gender),
            status: Number(formData.status),
            deptId: Number(formData.deptId),
            roleId: Number(formData.roleId),
            image: formData.image,
            remark: formData.remark
          }
          // 如果填写了密码，则包含密码字段
          if (formData.password) {
            submitData.password = formData.password
          }
          
          response = await axios.put('/api/users', submitData)
        } else {
          // 添加
          response = await axios.post('/api/users', {
            username: formData.username,
            password: formData.password,
            name: formData.name,
            phone: formData.phone,
            email: formData.email,
            gender: Number(formData.gender),
            status: Number(formData.status),
            deptId: Number(formData.deptId),
            roleId: Number(formData.roleId),
            image: formData.image,
            remark: formData.remark
          })
        }
        
        const result = response.data
        if (result.code === 1) {
          ElMessage.success(formData.id ? '修改成功' : '添加成功')
          dialogVisible.value = false
          getUserList()
        } else {
          ElMessage.error(result.msg || (formData.id ? '修改失败' : '添加失败'))
        }
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
    
    // 关闭对话框
    const handleClose = () => {
      resetForm()
    }
    
    // 分页大小改变
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      pagination.currentPage = 1
      getUserList()
    }
    
    // 当前页码改变
    const handleCurrentChange = (current) => {
      pagination.currentPage = current
      getUserList()
    }
    
    // 处理选择变化
    const handleSelectionChange = (rows) => {
      selectedRows.value = rows
    }
    
    // 页面加载时获取数据
    onMounted(async () => {
      // 先加载部门和角色选项
      await Promise.all([loadDeptOptions(), loadRoleOptions()])
      // 然后获取用户列表
      getUserList()
    })
    
    return {
      searchForm,
      userList,
      pagination,
      dialogVisible,
      dialogTitle,
      formRef,
      formData,
      formRules,
      deptOptions,
      roleOptions,
      selectedRows,
      getUserList,
      handleSearch,
      handleReset,
      handleAdd,
      handleEdit,
      handleDelete,
      handleBatchCheck,
      handleSubmit,
      handleClose,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.search-form {
  margin-bottom: 15px;
}

.action-buttons {
  text-align: right;
  margin-bottom: 15px;
}

.action-buttons-left {
  text-align: left;
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表格样式优化 */
:deep(.el-table__row) {
  height: 45px;
}

/* 调整列间距 */
:deep(.el-table__cell) {
  padding: 12px 15px;
  font-size: 14px;
  min-width: fit-content;
}

/* 调整表单输入框宽度 */
.el-form .el-input,
.el-form .el-select {
  width: 100%;
}

/* 主内容滚动容器 - 服务于整个页面内容 */
.main-content-wrapper {
  overflow-x: auto; /* 确保水平滚动条始终显示 */
  overflow-y: auto; /* 垂直滚动 */
  max-height: calc(100vh - 100px); /* 根据页面高度动态调整，确保足够空间 */
  position: relative;
  min-height: 600px;
  padding: 0 15px;
  white-space: nowrap; /* 防止内容自动换行 */
}

/* 确保卡片内容可以水平滚动 */
.main-content-wrapper > .el-card {
  white-space: nowrap;
  display: inline-block;
  width: 100%;
  min-width: 1320px; /* 确保表格有足够的最小宽度 */
}

/* 自定义滚动条样式 */
.main-content-wrapper::-webkit-scrollbar {
  height: 10px; /* 水平滚动条高度 */
  width: 10px;  /* 垂直滚动条宽度 */
}

.main-content-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 5px;
}

.main-content-wrapper::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 5px;
}

.main-content-wrapper::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 确保表格内容在滚动时不会溢出 */
:deep(.el-table) {
  min-width: 100%;
  width: auto;
  margin-bottom: 0;
}

/* 调整操作按钮样式 */
:deep(.el-button--small) {
  padding: 4px 12px;
  font-size: 12px;
}
</style>
